﻿using GBT.Tool.Core;
using GBT.Tool.Core.ToolHelps;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using ReportMealManagementSystem.Business;
using ReportMealManagementSystem.Entity;
using System;
using System.Configuration;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;

namespace ReportMealManagementSystem
{
    /// <summary>
    /// Login.xaml 的交互逻辑
    /// </summary>
    public partial class Login : Window
    {
        private Logger logger = LogManager.GetCurrentClassLogger();
        Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        UserManage userManage = new UserManage();
        Tools tools = new Tools();
        int districtID = int.Parse(ConfigurationManager.AppSettings["districtID"]);
        string number = ConfigurationManager.AppSettings["number"];
        string password = ConfigurationManager.AppSettings["password"];

        public Login()
        {
            InitializeComponent();
        }

        [DllImport("user32.dll")]
        public static extern int MessageBoxTimeoutA(IntPtr hWnd, string msg, string Caps, int type, int Id, int time); //引用DLL

        private void WLogin_Loaded(object sender, RoutedEventArgs e)
        {
            this.Left = 0.0;
            this.Top = 0.0;
            this.Width = SystemParameters.PrimaryScreenWidth;
            this.Height = SystemParameters.WorkArea.Height;
            
            number = cfa.AppSettings.Settings["number"].Value;
            password = cfa.AppSettings.Settings["password"].Value;
            var remember = bool.Parse(cfa.AppSettings.Settings["remember"].Value);
            if (remember)
            {
                cbIsRememb.IsChecked = true;
                if (!string.IsNullOrWhiteSpace(password))
                {
                    pbPassword.Password = password;
                }
            }
            else
            {
                cfa.AppSettings.Settings["password"].Value = "";
                cbIsRememb.IsChecked = false;
                cfa.Save();
            }

            if (!string.IsNullOrWhiteSpace(number))
            {
                txtUserNumber.Text = number;
            }
        }

        private void UserLogin()
        {
            JObject joParam = new JObject();
            if (string.IsNullOrWhiteSpace(number))
            {
                joParam["Number"] = txtUserNumber.Text.Trim();
                cfa.AppSettings.Settings["number"].Value = txtUserNumber.Text.Trim();
            }
            else
            {
                if (txtUserNumber.Text.Trim() != number)
                {
                    //输入的工号和配置文件不一样则更新
                    number = txtUserNumber.Text.Trim();
                    cfa.AppSettings.Settings["number"].Value = number;
                }
                txtUserNumber.Text = number;
                joParam["Number"] = number;
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                password = Encryption.Get_MD5(pbPassword.Password.Trim());
                joParam["password"] = password;
            }
            else
            {
                if (password.Length < 32 && Encryption.Get_MD5(pbPassword.Password.Trim()) != password)
                {
                    //输入的密码和配置文件不一样则更新
                    password = Encryption.Get_MD5(pbPassword.Password.Trim());
                    cfa.AppSettings.Settings["password"].Value = password;
                }
                pbPassword.Password = password;
                joParam["password"] = password;
            }

            if (cbIsRememb.IsChecked == true)
            {
                cfa.AppSettings.Settings["password"].Value = password;
            }
            else
            {
                cfa.AppSettings.Settings["password"].Value = "";
            }
            cfa.Save();
            joParam["districtID"] = districtID;
            bool isLogin = false;
            _loading.Visibility = Visibility.Visible;
            string msg = "";
            JObject joUserInfo = new JObject();
            Task task = new Task(new Action(delegate {
                logger.Info(joParam.ToString());
                isLogin = userManage.loginVerify(joParam, ref msg, ref joUserInfo);
                if (isLogin)
                {
                    Global.MealUser = JsonConvert.DeserializeObject<MealUser>(joUserInfo.ToString());
                    logger.Info(joUserInfo.ToString());
                    this.Dispatcher.Invoke(new Action(delegate
                    {
                        MainWindow mainWindow = new MainWindow();
                        mainWindow.Show();
                        this.Close();
                    }));
                }
                else
                {
                    cfa.AppSettings.Settings["password"].Value = "";
                    cfa.Save();
                    MessageBoxTimeoutA((IntPtr)0, msg, "温馨提示", 0, 0, 2000); // 直接调用 2秒后自动关闭
                }
            }));
            task.Start();
            task.ContinueWith((t) => {
                _loading.Dispatcher.Invoke(new Action(delegate {
                    _loading.Visibility = Visibility.Collapsed;
                }));
            });
        }

        private void PasswordBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                UserLogin();
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            UserLogin();
        }

        private void Button_TouchUp(object sender, System.Windows.Input.TouchEventArgs e)
        {
            //UserLogin();
        }

        private void TextBlock_TouchUp(object sender, System.Windows.Input.TouchEventArgs e)
        {
            LoginBox.Visibility = Visibility.Collapsed;
            ModifyPassword.Visibility = Visibility.Visible;
        }

        private void TextBlock_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            LoginBox.Visibility = Visibility.Collapsed;
            ModifyPassword.Visibility = Visibility.Visible;
        }

        private void UserModifyPassword()
        {
            JObject joParma = new JObject();
            joParma["mobile"] = txtMobile.Text;
            joParma["oldPassword"] = Encryption.Get_MD5(pbOldPassword.Password);
            joParma["password"] = Encryption.Get_MD5(pbNewPassword.Password);
            joParma["districtID"] = districtID;
            bool isModify = false;
            _loading.Visibility = Visibility.Visible;
            string msg = "";
            Task task = new Task(new Action(delegate {
                isModify = userManage.UserModifyPassword(joParma, ref msg);
                if (isModify)
                {
                    LoginBox.Dispatcher.Invoke(new Action(delegate
                    {
                        MessageBoxTimeoutA((IntPtr)0, msg, "温馨提示", 0, 0, 2000); // 直接调用 2秒后自动关闭
                        LoginBox.Visibility = Visibility.Visible;
                        ModifyPassword.Visibility = Visibility.Collapsed;
                        txtMobile.Text = "";
                        pbOldPassword.Password = "";
                        pbNewPassword.Password = "";
                    }));
                }
                else
                {
                    MessageBoxTimeoutA((IntPtr)0, msg, "温馨提示", 0, 0, 2000); // 直接调用 2秒后自动关闭
                }
            }));
            task.Start();
            task.ContinueWith((t) => {
                _loading.Dispatcher.Invoke(new Action(delegate {
                    _loading.Visibility = Visibility.Collapsed;
                }));
            });
        }

        private void Modify_Click(object sender, RoutedEventArgs e)
        {
            UserModifyPassword();
        }

        private void Close_Click(object sender, RoutedEventArgs e)
        {
            LoginBox.Visibility = Visibility.Visible;
            ModifyPassword.Visibility = Visibility.Collapsed;
        }

        private void CommandBinding_AutoStart_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void CommandBinding_AutoStart_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
        {
            
        }

        private void CommandBinding_UnAutoStart_CanExecute(object sender, System.Windows.Input.CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void CommandBinding_UnAutoStart_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
        {
            
        }

        private void CbIsRememb_Checked(object sender, RoutedEventArgs e)
        {

        }

        private void CbIsRememb_Click(object sender, RoutedEventArgs e)
        {
            if (cbIsRememb.IsChecked == true)
            {
                cfa.AppSettings.Settings["remember"].Value = "true";
            }
            else
            {
                cfa.AppSettings.Settings["remember"].Value = "false";
                cfa.AppSettings.Settings["password"].Value = "";
            }
            cfa.Save();
        }

        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}
